package com.junwei.webfluxdemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

//import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName TestController
 * @Description reactor = jdk8 stream + jdk9 reactive stream
 * Mono 0-1 个元素
 * Flux 0-N个元素
 * @Author 王军伟
 * @Date 2020/2/23 下午5:03
 */
@Slf4j
@RestController
@RequestMapping("test")
public class TestController {
    /**
     * localhost:8080/test/get
     * @return
     */
    @GetMapping("get")
    private Mono<String> get() {
        log.info("start");
        Mono<String> result = Mono.fromSupplier(this::createStr);
        log.info("end");
        return result;
    }

    /**
     * localhost:8080/test/flux
     * @return
     */
    @GetMapping(value = "flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    private Flux<String> flux() {
        return Flux.fromStream(IntStream.range(1, 15).mapToObj(it -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException ignored) {
            }
            return "flux data--" + it;
        }));
    }

    /**
     * localhost:8080/test/bootMvc
     * @return
     */
    @GetMapping(value = "bootMvc")
    private String bootMvc() throws InterruptedException {
        IntStream.range(1, 15).mapToObj(it -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException ignored) {
            }
            return "flux data--" + it;
        });
        return null;
    }

    /*@GetMapping(value = "get")
    private void get(HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("utf-8");
        for (int i = 0; i < 5; i++) {
            response.getWriter().write("data:" + i + "\n");
            response.getWriter().flush();
            TimeUnit.SECONDS.sleep(1);
        }
    }*/

    private String createStr() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "some string";
    }
}
